package com.xykj.enterprise.wechat.ext.api.externalcontact;

import com.xykj.enterprise.wechat.bean.ext.externalcontact.GroupChatListVo;
import com.xykj.enterprise.wechat.ext.service.customer.ExternalContactService;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;

@Slf4j
@Function(description = "获取客户群列表", parameters = {
        @Parameter(name = "access_token", type = Type.String, description = "access_token", required = true),

        @Parameter(name = "status_filter", type = Type.Integer, description = "客户群跟进状态过滤。 0所有列表(即不过滤) 1离职待继承 2离职继承中 3离职继承完成 默认为0", required = false),
        @Parameter(name = "owner_filter", type = Type.String, description = "群主过滤。如果不填，表示获取应用可见范围内全部群主的数据（但是不建议这么用，如果可见范围人数超过1000人，为了防止数据包过大，会报错 81017）", required = false),
        @Parameter(name = "cursor", type = Type.String, description = "用于分页查询的游标，字符串类型，由上一次调用返回，首次调用不填", required = false),
        @Parameter(name = "limit", type = Type.Integer, description = "分页，预期请求的数据量，取值范围 1 ~ 1000", required = true),
})
@Component
public class GetGroupChatList implements Action {

    @Autowired
    private ExternalContactService externalContactService;

    @Override
    public Response execute(Request request) throws Exception {
        Integer status_filter = request.getInteger("status_filter");
        Integer limit = request.getInteger("limit");
        String owner_filter = request.getString("owner_filter");
        String cursor = request.getString("cursor");
        HashMap<String, Object> params = new HashMap<String, Object>();
        if (status_filter != null) {
            params.put("status_filter", status_filter);
        }
        if (owner_filter != null) {
            String[] ownerFilterSplit = owner_filter.split(",");
            ArrayList<String> tmpList = new ArrayList<String>();
            for (String str :
                    ownerFilterSplit) {
                tmpList.add(str);
            }
            HashMap<String, ArrayList<String>> ownerFilerObj = new HashMap<String, ArrayList<String>>();
            ownerFilerObj.put("userid_list", tmpList);
            params.put("owner_filter", ownerFilerObj);
        }
        if (cursor != null) {
            params.put("cursor", cursor);
        }
        params.put("limit", limit);

        GroupChatListVo rsp = externalContactService.getGroupChatList(
                request.getString("access_token"), params
        );
        if (rsp.getErrcode() != 0) {
            return Response.fail(rsp.getErrmsg());
        }
        return Response.success().put("data", rsp);
    }
}
